﻿using System;
using System.Windows.Forms;
//using Adpater;
using DevExpress.XtraTreeList.Nodes;
using Common;
using DevExpress.XtraTreeList;
using Controller;
using Model;
using System.Collections;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Data;
using DevExpress.XtraEditors;
using System.Drawing;


namespace CodeFactory
{
    public partial class DesignForm : ContentWindow
    {

        #region 私有字段
        /// <summary>
        /// 用于命名后缀防止重名
        /// </summary>
        int index = 0;
        int indexLay = 1;
        string currentBuildName = "";
        int oldParentID = 0;
        private PropertyGridBO _pgBO;
        public PropertyGridBO pgBO
        {
            get
            {
                if (_pgBO == null)
                    _pgBO = FactoryControllerBO.CurrentFA.CreateProperGridBOInstance();
                return _pgBO;
            }

        }

        private CoreBO _coreBO;
        public CoreBO coreBO
        {
            get
            {
                if (_coreBO == null)
                    _coreBO = FactoryControllerBO.CurrentFA.CreateCoreBOInstance();
                return _coreBO;
            }
        }
        #endregion


        #region 初始化

        public DesignForm()
        {
            InitializeComponent();
        }
        public DesignForm(CSharpSourceForm cf, XMLSourceForm xf, CSharpSourceDesign cd)
        {
            InitializeComponent();
        }


        private void DesignForm_Load(object sender, EventArgs e)
        {
            
        }
        #endregion


        #region 公共方法可供外部调用

        /// <summary>
        /// 是不是所有的控件都在布局空间里面
        /// 0:格式正确 
        /// 1：控件都在布局中，但是还有空的Item，生成时忽略空的 
        /// 2：不是所有控件都在布局中，返回重试
        /// 3：含有空的Group，生成时将出错，请返回删除
        /// </summary>
        /// <returns></returns>
        public int IsAllControlInLayout()
        {
            if (treeLayout.Nodes.Count < 1)
            {
                return 0;
            }
            int num = treeControls.Nodes.Count;
            int numItem = 0;
            int numItemIn = 0;

            for (int i = 0; i < treeLayout.AllNodesCount; i++)
            {
                if (treeLayout.FindNodeByID(i).GetValue(0).ToString() == "Group")
                {
                    if (!treeLayout.FindNodeByID(i).HasChildren)
                    {
                        return 3;
                    }
                }
                if (treeLayout.FindNodeByID(i).GetValue(0).ToString() == "Item")
                {
                    numItem++;
                    if (treeLayout.FindNodeByID(i).GetValue(1) != null)
                    {
                        if (!String.IsNullOrEmpty(treeLayout.FindNodeByID(i).GetValue(1).ToString()))
                        {
                            numItemIn++;
                        }
                    }
                }
            }
            if (numItemIn == num)
            {
                if (numItem > num)
                {
                    return 1;
                }
                else
                {
                    return 0;
                }
            }

            return 2;
        }


        /// <summary>
        /// 生成XML
        /// </summary>
        public void BuildXMLCode(XMLSourceForm xsf, string path)
        {
            //string path = PubConstant.ControlXmlTemplatePath;
            path = String.Format("{0}Build.xml", path);
            coreBO.BuildXMLCode(customPropertyGrid1.buildDic, path);
            xsf.SetText(path);
        }

        /// <summary>
        /// 生成C#
        /// </summary>
        /// <param name="cssf"></param>
        /// <param name="cssd"></param>
        public void BuildCSharpCode(CSharpSourceForm cssf, CSharpSourceDesign cssd, string path)
        {
            //string xmlPath = PubConstant.ControlXmlTemplatePath;
            string xmlPath = String.Format("{0}Build.xml", path);
            Hashtable ht = coreBO.BuildCSharpCode(xmlPath);
            cssf.SetText(ht["Code1"].ToString());//.CS文件
            cssd.SetText(ht["Code2"].ToString());//.Design.CS文件


            //将两个代码文件写到本地
            using (StreamWriter sw = new StreamWriter(path + "Build.cs", false, Encoding.UTF8))
            {
                sw.WriteLine(ht["Code1"].ToString());
            }
            using (StreamWriter sw = new StreamWriter(path + "Build.Design.cs", false, Encoding.UTF8))
            {
                sw.WriteLine(ht["Code2"].ToString());
            }

        }


        /*=======================================================================================*/


        /// <summary>
        /// 设计区是否是隐藏状态
        /// </summary>
        /// <returns></returns>
        public bool IsHide()
        {
            if (splitMain.Visible)
            {
                return false;
            }
            else
            {
                return true;
            }
        }


        /// <summary>
        /// 清空所有树的信息
        /// </summary>
        public void CleanAllTree()
        {
            treeBaseControl.Nodes.Clear();
            treeControls.Nodes.Clear();
            treeLayout.Nodes.Clear();
            treeItemForPopup.Nodes.Clear();
            customPropertyGrid1.PropertyTree.Nodes.Clear();
        }



        /// <summary>
        /// 从控件边栏添加一个控件
        /// </summary>
        /// <param name="tbItem">System.Drawing.Design.ToolboxItem</param>
        /// <param name="BuildName">控件的生成名称</param>
        /// <param name="Field">控件对应字段</param>
        /// <param name="ControlType">控件的类型（Win，Dev，Web）</param>
        public void AddControlsToTree(System.Drawing.Design.ToolboxItem tbItem, string BuildName, string Field, string ControlType,string LayoutText)
        {
            BuildName = CreateNoRepeatBuildName(BuildName);
            TreeListNode tln = treeControls.AppendNode(null, null);
            tln.SetValue(0, tbItem.DisplayName);
            tln.SetValue(1, String.IsNullOrEmpty(BuildName) ? "default" + index.ToString() : BuildName);
            tln.SetValue(2, Field);
            tln.SetValue(3, String.Format("{0}, {1}", tbItem.TypeName, tbItem.AssemblyName));
            tln.SetValue(4, ControlType);
            tln.SetValue(5, LayoutText);
            imageList1.Images.Add(tbItem.Bitmap);
            tln.ImageIndex = imageList1.Images.Count - 1; //控件里默认已经有了2个图标
            tln.StateImageIndex = imageList1.Images.Count - 1;

            exFullInfoForBuildChild exInfo = new exFullInfoForBuildChild();
            exInfo.ControlName = treeControls.Nodes.LastNode[0].ToString();//treeControls.Nodes.LastNode为定位到新添加的控件
            exInfo.BuildName = treeControls.Nodes.LastNode[1].ToString();
            exInfo.ControlFullName = treeControls.Nodes.LastNode[3].ToString();
            exInfo.ControlClass = treeControls.Nodes.LastNode[4].ToString();
            exInfo.LayoutText = treeControls.Nodes.LastNode[5].ToString();
            exInfo.IsBase = false;

            customPropertyGrid1.SetButtonStatus(false, false);
            customPropertyGrid1.ChangePropertyButtonState(false);
            customPropertyGrid1.GetPropertyToGrid(exInfo, enumPropertyType.Property, true);
        }



        /// <summary>
        /// 获取控件缩写名称
        /// </summary>
        /// <param name="ControlType">控件的类型（TextBox,Label等）</param>
        /// <param name="ControlClass">控件的种类（WinForm，DevExpress等）</param>
        public string GetPrefixOfControl(string ControlType, string ControlClass)
        {
            return pgBO.GetPrefixOfControl(ControlType, ControlClass);
        }



        /// <summary>
        /// 添加一个基底
        /// </summary>
        /// <param name="BaseType"></param>
        /// <param name="BaseControlName"></param>
        public void AddBaseControlToTree(enumBaseControlType BaseType)
        {
            TreeListNode tln = treeBaseControl.AppendNode(null, null);

            exFullInfoForBuildChild exFinfo = pgBO.GetBaseTypeInfoFromTemplate(BaseType);
            switch (BaseType)
            {
                case enumBaseControlType.XtraUserControl:
                    tln.ImageIndex = 1;
                    tln.StateImageIndex = 1;
                    tln.SetValue(0, enumBaseControlType.XtraUserControl.ToString());
                    tln.SetValue(1, exFinfo.BuildName);
                    tln.SetValue(2, exFinfo.ControlFullName);
                    break;
                case enumBaseControlType.XtraForm:
                    tln.ImageIndex = 0;
                    tln.StateImageIndex = 0;
                    tln.SetValue(0, enumBaseControlType.XtraForm.ToString());
                    tln.SetValue(1, exFinfo.BuildName);
                    tln.SetValue(2, exFinfo.ControlFullName);
                    break;
                case enumBaseControlType.RibbonForm:
                    tln.ImageIndex = 0;
                    tln.StateImageIndex = 0;
                    tln.SetValue(0, enumBaseControlType.RibbonForm.ToString());
                    tln.SetValue(1, exFinfo.BuildName);
                    tln.SetValue(2, exFinfo.ControlFullName);
                    break;
                case enumBaseControlType.UserControl:
                    tln.ImageIndex = 1;
                    tln.StateImageIndex = 1;
                    tln.SetValue(0, enumBaseControlType.UserControl.ToString());
                    tln.SetValue(1, exFinfo.BuildName);
                    tln.SetValue(2, exFinfo.ControlFullName);
                    break;
                case enumBaseControlType.Form:
                    tln.ImageIndex = 0;
                    tln.StateImageIndex = 0;
                    tln.SetValue(0, enumBaseControlType.Form.ToString());
                    tln.SetValue(1, exFinfo.BuildName);
                    tln.SetValue(2, exFinfo.ControlFullName);
                    break;

            }
            customPropertyGrid1.GetDocumentToGrid(BaseType);
        }



        /// <summary>
        /// 设置设计器设计区是否被隐藏
        /// 清除上次工程的缓存
        /// </summary>
        /// <param name="IsHide"></param>
        public void SetDesignAreaHide(bool IsHide)
        {
            if (IsHide)
            {
                splitMain.Visible = false;
            }
            else
            {
                splitMain.Visible = true;
            }
            customPropertyGrid1.dicClean();

        }



        /// <summary>
        /// 生成名字中是否有重复项
        /// </summary>
        /// <returns></returns>
        public bool HasRepeatName()
        {
            foreach (TreeListNode tln in treeControls.Nodes)
            {
                int num = 0;
                foreach (TreeListNode tl in treeControls.Nodes)
                {
                    if (String.Compare(tln.GetValue(1).ToString(), tl.GetValue(1).ToString(), false) == 0)
                    {
                        num++;
                    }
                }
                if (num > 1)
                {
                    return true;
                }
            }
            return false;
        }

        #endregion


        #region 私有方法
        //---------------------------------------------------------------------
        /// <summary>
        /// 返回有多少个相同的,如果为空则给默认值
        /// </summary>
        /// <param name="BuildName"></param>
        /// <returns></returns>
        private string CreateNoRepeatBuildName(string BuildName)
        {
            int num = 0;
            if (String.IsNullOrEmpty(BuildName))
            {
                BuildName = "default";
            }
            foreach (TreeListNode tln in treeControls.Nodes)
            {
                if (tln.GetValue(1).ToString().Equals(BuildName))
                {
                    num++;
                }
            }
            if (num > 0)
            {
                index++;
                BuildName += index.ToString();
            }
            return BuildName;
        }

        /// <summary>
        /// 为布局控件新建不重复的名称
        /// </summary>
        /// <param name="enumLay"></param>
        /// <returns></returns>
        private string CreateNoRepeatLayoutName(enumLayoutTypeSimple enumLay)
        {
            string sname = null;

            switch (enumLay)
            {
                case enumLayoutTypeSimple.Base:
                    sname = "layoutControl";
                    break;
                case enumLayoutTypeSimple.Group:
                    sname = "layoutControlGroup";
                    break;
                case enumLayoutTypeSimple.Item:
                    sname = "layoutControlItem";
                    break;
                case enumLayoutTypeSimple.EmptyItem:
                    sname = "emptySpaceItem";
                    break;
            }

            if (HasSameName(sname + indexLay.ToString(), false))
            {
                indexLay++;
            }

            return sname + indexLay.ToString();
        }

        private bool HasSameName(string name, bool IsControl)
        {
            int num = 0;
            for (int i = 0; i < treeLayout.AllNodesCount; i++)
            {
                if (IsControl)
                {
                    if (treeLayout.FindNodeByID(i).GetValue(1) != null)
                    {
                        if (treeLayout.FindNodeByID(i).GetValue(1).ToString().Equals(name))
                        {
                            num++;
                        }
                    }
                    if (num > 1)
                    {
                        return true;
                    }
                }
                else
                {
                    if (treeLayout.FindNodeByID(i).GetValue(4) != null)
                    {
                        if (treeLayout.FindNodeByID(i).GetValue(4).ToString().Equals(name))
                        {
                            num++;
                        }
                    }
                    if (num > 0)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        //----------------------------------------------------------------------
        public void CreateNewLayoutForBuild(exFullInfoForBuild exFIFB)
        {
            CreateNewLayoutItem(enumLayoutTypeSimple.Base);
            TreeListNode node=treeLayout.FindNodeByFieldValue("ItemType", "Group");
            foreach (exFullInfoForBuildChild exFIBC in exFIFB.list)
            {
                TreeListNode tln = treeLayout.AppendNode(null, node.Id);
                tln.SetValue(0, enumLayoutTypeSimple.Item.ToString());
                tln.SetValue(1, exFIBC.BuildName);
                tln.SetValue(2, enumLayoutType.LayoutControlItem.ToString());
                tln.SetValue(3, "DevExpress.XtraLayout.LayoutControlItem, " + PubConstant.XtraLayoutAssembly);
                tln.SetValue(4, CreateNoRepeatLayoutName(enumLayoutTypeSimple.Item));
                tln.SetValue(5, exFIBC.LayoutText);
                tln.SetValue(6, node.GetValue(4).ToString());

                //把新生成的LayoutItem存入内存
                exFullInfoForBuildChild exLayout = new exFullInfoForBuildChild();
                exLayout.LayoutType = (enumLayoutTypeSimple)Enum.Parse(typeof(enumLayoutTypeSimple), tln[0].ToString());
                exLayout.InControl = tln[1] == null ? "" : tln[1].ToString();
                exLayout.ControlName = tln[2].ToString();
                exLayout.ControlFullName = tln[3].ToString();
                exLayout.BuildName = tln[4].ToString();
                exLayout.LayoutText = tln[5] == null ? "" : tln[5].ToString();
                exLayout.ParentLayoutName = tln[6] == null ? "" : tln[6].ToString();
                exLayout.IsLayout = true;
                exLayout.IsBase = false;
                customPropertyGrid1.GetLayoutToGrid(exLayout);
            }
            treeLayout.ExpandAll();
            
        }

        /// <summary>
        /// 新建一个Layout
        /// </summary>
        /// <param name="enumLay"></param>
        private void CreateNewLayoutItem(enumLayoutTypeSimple enumLay)
        {
            switch (enumLay)
            {
                case enumLayoutTypeSimple.Base://1为包括的控件名5为Text
                    TreeListNode tln1 = treeLayout.AppendNode(null, null);
                    tln1.SetValue(0, enumLayoutTypeSimple.Base.ToString());//类型
                    tln1.SetValue(2, enumLayoutType.LayoutControl.ToString());//完整类型
                    tln1.SetValue(3, "DevExpress.XtraLayout.LayoutControl, " + PubConstant.XtraLayoutAssembly);//程序集
                    tln1.SetValue(4, CreateNoRepeatLayoutName(enumLay));//buildName
                    tln1.SetValue(6, "");//父节点ID
                    treeLayout.SetFocusedNode(tln1);
                    LayoutClickAndGetLayoutInfo();
                    TreeListNode tlnGroup = treeLayout.AppendNode(null, tln1.Id);
                    tlnGroup.SetValue(0, enumLayoutTypeSimple.Group.ToString());
                    tlnGroup.SetValue(2, enumLayoutType.LayoutControlGroup.ToString());
                    tlnGroup.SetValue(3, "DevExpress.XtraLayout.LayoutControlGroup, " + PubConstant.XtraLayoutAssembly);
                    tlnGroup.SetValue(4, CreateNoRepeatLayoutName(enumLayoutTypeSimple.Group));
                    tlnGroup.SetValue(6, tln1.GetValue(4).ToString());
                    treeLayout.SetFocusedNode(tlnGroup);
                    break;
                case enumLayoutTypeSimple.Group:
                    TreeListNode tln2 = treeLayout.AppendNode(null, treeLayout.FocusedNode.Id);
                    tln2.SetValue(0, enumLayoutTypeSimple.Group.ToString());
                    tln2.SetValue(2, enumLayoutType.LayoutControlGroup.ToString());
                    tln2.SetValue(3, "DevExpress.XtraLayout.LayoutControlGroup, " + PubConstant.XtraLayoutAssembly);
                    tln2.SetValue(4, CreateNoRepeatLayoutName(enumLay));
                    tln2.SetValue(6, treeLayout.FocusedNode.GetValue(4).ToString());
                    break;
                case enumLayoutTypeSimple.Item:
                    TreeListNode tln3 = treeLayout.AppendNode(null, treeLayout.FocusedNode.Id);
                    tln3.SetValue(0, enumLayoutTypeSimple.Item.ToString());
                    tln3.SetValue(2, enumLayoutType.LayoutControlItem.ToString());
                    tln3.SetValue(3, "DevExpress.XtraLayout.LayoutControlItem, " + PubConstant.XtraLayoutAssembly);
                    tln3.SetValue(4, CreateNoRepeatLayoutName(enumLay));
                    tln3.SetValue(6, treeLayout.FocusedNode.GetValue(4).ToString());
                    break;
                case enumLayoutTypeSimple.EmptyItem:
                    TreeListNode tln4 = treeLayout.AppendNode(null, treeLayout.FocusedNode.Id);
                    tln4.SetValue(0, enumLayoutTypeSimple.EmptyItem.ToString());
                    tln4.SetValue(2, enumLayoutType.EmptySpaceItem.ToString());
                    tln4.SetValue(3, "DevExpress.XtraLayout.EmptySpaceItem, " + PubConstant.XtraLayoutAssembly);
                    tln4.SetValue(4, CreateNoRepeatLayoutName(enumLay));
                    tln4.SetValue(6, treeLayout.FocusedNode.GetValue(4).ToString());
                    break;
            }
            treeLayout.ExpandAll();

            //把最新增加的控件存入内存
            exFullInfoForBuildChild exLayout = new exFullInfoForBuildChild();
            TreeListNode fnode = treeLayout.FindNodeByID(treeLayout.AllNodesCount - 1);
            exLayout.LayoutType = (enumLayoutTypeSimple)Enum.Parse(typeof(enumLayoutTypeSimple), fnode[0].ToString());
            exLayout.InControl = fnode[1] == null ? "" : fnode[1].ToString();
            exLayout.ControlName = fnode[2].ToString();
            exLayout.ControlFullName = fnode[3].ToString();
            exLayout.BuildName = fnode[4].ToString();
            exLayout.LayoutText = fnode[5] == null ? "" : fnode[5].ToString();
            exLayout.ParentLayoutName = fnode[6] == null ? "" : fnode[6].ToString();
            exLayout.IsLayout = true;
            exLayout.IsBase = false;

            if (exLayout.LayoutType == enumLayoutTypeSimple.Base)
            {
                List<string> list = new List<string>();
                foreach (TreeListNode tn in treeControls.Nodes)
                {
                    list.Add(tn.GetValue(1) == null ? "" : tn.GetValue(1).ToString());
                }
                exLayout.ControlsList = list;
            }

            


            customPropertyGrid1.SetButtonStatus(false, true);
            customPropertyGrid1.ChangePropertyButtonState(true);
            customPropertyGrid1.GetLayoutToGrid(exLayout);
        }


        /// <summary>
        /// 收集基底信息然后跳转到右边属性，可用于刷新
        /// </summary>
        private void BaseClickAndGetBaseInfo()
        {
            exFullInfoForBuildChild exInfo = new exFullInfoForBuildChild();
            exInfo.ControlName = treeBaseControl.FocusedNode[0].ToString();
            exInfo.BuildName = treeBaseControl.FocusedNode[1].ToString();
            exInfo.ControlFullName = treeBaseControl.FocusedNode[2].ToString();
            exInfo.IsBase = true;
            //exInfo.ControlClass = treeBaseControl.FocusedNode[3].ToString();

            customPropertyGrid1.ChangePropertyButtonState(false);
            customPropertyGrid1.SetButtonStatus(true, false);
            customPropertyGrid1.GetPropertyToGridBase(exInfo, enumPropertyType.Property, true);
        }

        /// <summary>
        /// 收集控件信息然后跳转到右边属性，可用于刷新
        /// </summary>
        private void ControlClickAndGetControlInfo()
        {
            exFullInfoForBuildChild exInfo = new exFullInfoForBuildChild();
            exInfo.ControlName = treeControls.FocusedNode[0].ToString();
            exInfo.BuildName = treeControls.FocusedNode[1].ToString();
            exInfo.ControlFullName = treeControls.FocusedNode[3].ToString();
            exInfo.ControlClass = treeControls.FocusedNode[4].ToString();
            exInfo.IsBase = false;

            customPropertyGrid1.SetButtonStatus(false, false);
            customPropertyGrid1.ChangePropertyButtonState(false);
            customPropertyGrid1.GetPropertyToGrid(exInfo, enumPropertyType.Property, true);

        }

        /// <summary>
        /// 收集布局控件信息然后跳转到右边属性，可用于刷新
        /// </summary>
        private void LayoutClickAndGetLayoutInfo()
        {
            exFullInfoForBuildChild exLayout = new exFullInfoForBuildChild();
            exLayout.LayoutType = (enumLayoutTypeSimple)Enum.Parse(typeof(enumLayoutTypeSimple), treeLayout.FocusedNode[0].ToString());
            exLayout.InControl = treeLayout.FocusedNode[1] == null ? "" : treeLayout.FocusedNode[1].ToString();
            exLayout.ControlName = treeLayout.FocusedNode[2].ToString();
            exLayout.ControlFullName = treeLayout.FocusedNode[3].ToString();
            exLayout.BuildName = treeLayout.FocusedNode[4].ToString();
            exLayout.LayoutText = treeLayout.FocusedNode[5] == null ? "" : treeLayout.FocusedNode[5].ToString();
            exLayout.ParentLayoutName = treeLayout.FocusedNode[6] == null ? "" : treeLayout.FocusedNode[6].ToString();
            exLayout.IsLayout = true;
            exLayout.IsBase = false;

            if (exLayout.LayoutType == enumLayoutTypeSimple.Base)
            {
                List<string> list = new List<string>();
                foreach (TreeListNode tn in treeControls.Nodes)
                {

                    list.Add(tn.GetValue(1) == null ? "" : tn.GetValue(1).ToString());
                }
                exLayout.ControlsList = list;
            }




            customPropertyGrid1.SetButtonStatus(false, true);
            customPropertyGrid1.ChangePropertyButtonState(true);
            customPropertyGrid1.GetLayoutToGrid(exLayout);
        }
        #endregion


        #region Tree事件

        /*基类树--------------------------------------------------------------------------------*/
        /// <summary>
        /// BaseTree单元格单击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeBaseControl_MouseClick(object sender, MouseEventArgs e)
        {
            TreeListHitInfo hitinfo = new TreeListHitInfo();
            hitinfo = treeBaseControl.CalcHitInfo(e.Location);

            //if mouse not click the nodes, do nothing;
            if (hitinfo.HitInfoType != HitInfoType.Cell)
            {
                return;
            }
            if (e.Button != MouseButtons.Left)
            {
                if (e.Button != MouseButtons.Right)
                {
                    return;
                }
            }

            try
            {
                currentBuildName = treeBaseControl.FocusedNode.GetValue(1).ToString();
                BaseClickAndGetBaseInfo();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        /// <summary>
        /// 修改BaseName
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeBaseControl_CellValueChanged(object sender, CellValueChangedEventArgs e)
        {
            try
            {
                BaseClickAndGetBaseInfo();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 点中编辑时获得焦点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeBaseControl_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                BaseClickAndGetBaseInfo();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }



        /*控件树--------------------------------------------------------------------------------*/
        /// <summary>
        /// ControlsTree单元格单击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeControls_MouseClick(object sender, MouseEventArgs e)
        {
            TreeListHitInfo hitinfo = new TreeListHitInfo();
            hitinfo = treeControls.CalcHitInfo(e.Location);

            //if mouse not click the nodes, do nothing;
            if (hitinfo.HitInfoType != HitInfoType.Cell)
            {
                return;
            }
            if (e.Button != MouseButtons.Left)
            {
                if (e.Button != MouseButtons.Right)
                {
                    return;
                }
            }
            if (treeControls.Nodes.Count < 1)
            {
                return;
            }
            try
            {
                currentBuildName = treeControls.FocusedNode.GetValue(1).ToString();
                ControlClickAndGetControlInfo();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 点中编辑时获得焦点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeControls_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                ControlClickAndGetControlInfo();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        /// <summary>
        /// 修改BuildName事件（要防止生成名称相同）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeControls_CellValueChanged(object sender, CellValueChangedEventArgs e)
        {
            if (e.Column.Name != "treeColumnN") return;
            int num = 0;
            foreach (TreeListNode tln in treeControls.Nodes)
            {
                if (String.Compare(tln.GetValue(1).ToString().Trim(), e.Value.ToString().Trim(), false) == 0)
                {
                    num++;
                }
            }
            if (num < 2)
            {
                //treeLayout.FindNodeByFieldValue("ControlName", customPropertyGrid1.exFullInfo.BuildName).SetValue(1, e.Value);
                e.Node.SetValue(1, e.Value);
                customPropertyGrid1.dicUpdateKey(customPropertyGrid1.exFullInfo.BuildName, e.Value.ToString().Trim());
                ControlClickAndGetControlInfo();
                return;
            }
            else
            {
                string newName = e.Value + "_new";
                MessageBox.Show("已有相同名称，请返回修改");
                e.Node.SetValue(1, newName);
                //treeLayout.FindNodeByFieldValue("ControlName", customPropertyGrid1.exFullInfo.BuildName).SetValue(1, newName);
                customPropertyGrid1.dicUpdateKey(customPropertyGrid1.exFullInfo.BuildName, newName);
                ControlClickAndGetControlInfo();
            }
        }

        /*布局树---------------------------------------------------------------------------------*/

        /// <summary>
        /// 布局树单击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeLayout_MouseClick(object sender, MouseEventArgs e)
        {
            TreeListHitInfo hitinfo = new TreeListHitInfo();
            hitinfo = treeLayout.CalcHitInfo(new Point(e.X, e.Y));

            //if mouse not click the nodes, do nothing;
            if (hitinfo.HitInfoType != HitInfoType.Cell)
            {
                return;
            }
            if (e.Button != MouseButtons.Left)
            {
                return;
            }
            if (treeLayout.Nodes.Count < 1)
            {
                return;
            }
            try
            {
                LayoutClickAndGetLayoutInfo();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 点中编辑时获得焦点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeLayout_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                LayoutClickAndGetLayoutInfo();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 布局树自定义事件绑定事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeLayout_CustomNodeCellEdit(object sender, GetCustomNodeCellEditEventArgs e)
        {
            if (e.Column.Name == "treeColumnLayoutItemType") return;
            if (e.Column.Name == "treeColumnLayBName") return;
            if (e.Column.Name == "treeColumnParentId") return;

            object obj = e.Node.GetValue(0);//取得类型这一栏
            if (obj == null) return;

            if (e.Column.Name == "treeColumnLayText")
            {
                switch (obj.ToString())
                {
                    case "Base": e.RepositoryItem = rsItemTextEditEmpty; break;
                    case "Group": e.RepositoryItem = rsItemTextEdit; break;
                    case "Item": e.RepositoryItem = rsItemTextEdit; break;
                    case "EmptyItem": e.RepositoryItem = rsItemTextEditEmpty; break;
                }
            }
            else if (e.Column.Name == "treeColumnCorrespondingControl")
            {
                switch (obj.ToString())
                {
                    case "Base": e.RepositoryItem = rsItemTextEditEmpty; break;
                    case "Group": e.RepositoryItem = rsItemTextEditEmpty; break;
                    case "Item": e.RepositoryItem = rsItemPopupContainerLayout; break;
                    case "EmptyItem": e.RepositoryItem = rsItemTextEditEmpty; break;
                }
            }
        }



        /// <summary>
        /// 布局树单元格值更改事件（防止同时选中同样的控件）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeLayout_CellValueChanged(object sender, CellValueChangedEventArgs e)
        {
            if (e.Column.Name == "treeColumnLayoutItemType") return;
            if (e.Column.Name == "treeColumnLayoutFullName") return;
            if (e.Column.Name == "treeColumnLayoutName") return;
            if (e.Column.Name == "treeColumnLayBName") return;
            if (e.Column.Name == "treeColumnParentId") return;
            //if (HasSameName(e.Value.ToString().Trim(), true))
            //{
            //    MessageBox.Show("已选择过相同控件，请返回修改");
            //    e.Node.SetValue(1, "");
            //    return;
            //}

            LayoutClickAndGetLayoutInfo();
        }





        /*控件下拉列表树-------------------------------------------------------------------*/
        /// <summary>
        /// 控件选择树单元格单击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeItemForPopup_MouseClick(object sender, MouseEventArgs e)
        {
            TreeListHitInfo hitinfo = new TreeListHitInfo();
            hitinfo = treeItemForPopup.CalcHitInfo(e.Location);

            //if mouse not click the nodes, do nothing;
            if (hitinfo.HitInfoType != HitInfoType.Cell)
            {
                return;
            }
            if (e.Button != MouseButtons.Left)
            {
                return;
            }
            if (popupContainerControl1.OwnerEdit != null)
            {
                popupContainerControl1.OwnerEdit.ClosePopup();
                //刷新控件列表，使得其焦点处于选中时的状态
                rsItemPopupContainerLayout.BeginUpdate();
                rsItemPopupContainerLayout.EndUpdate();
            }
        }


        /// <summary>
        /// 拖动后
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeLayout_AfterDragNode(object sender, NodeEventArgs e)
        {
            if (e.Node.Id == 1 && e.Node.ParentNode == null)//不能拖动基底Group
            {
                MessageBox.Show("不能拖动基底组");
                treeLayout.MoveNode(e.Node, treeLayout.FindNodeByID(0), true);
            }
            else if (e.Node.ParentNode == null || e.Node.ParentNode.Id == 0)//其他子节点不能拖到Base上也不能拖到Root上
            {
                MessageBox.Show("不能进行的拖放操作");
                treeLayout.MoveNode(e.Node, treeLayout.FindNodeByID(oldParentID), true);
            }
            else if (e.Node.ParentNode.GetValue(0).ToString() == "Item" || e.Node.ParentNode.GetValue(0).ToString() == "EmptyItem")
            {
                MessageBox.Show("Item不能有包含项");
                treeLayout.MoveNode(e.Node, treeLayout.FindNodeByID(oldParentID), true);
            }
            else
            {
                e.Node.SetValue(6, e.Node.ParentNode.GetValue(4));
            }
        }

        /// <summary>
        /// 拖动前
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeLayout_BeforeDragNode(object sender, BeforeDragNodeEventArgs e)
        {
            try
            {
                oldParentID = e.Node.ParentNode == null ? 0 : e.Node.ParentNode.Id;//记录拖动之前的父节点ID
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion


        #region 菜单事件

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void contentMenuItemDelete_Click(object sender, EventArgs e)
        {
            if (treeControls.FocusedNode != null)
            {
                customPropertyGrid1.treeProperty.Nodes.Clear();
                customPropertyGrid1.dicRemove(treeControls.FocusedNode.GetValue(1) == null ? "" : treeControls.FocusedNode.GetValue(1).ToString());
                treeControls.Nodes.Remove(treeControls.FocusedNode);
            }
        }

        /*布局菜单-----------------------------------------------------------------------*/
        /// <summary>
        /// 新Group
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuItemNewGroup_Click(object sender, EventArgs e)
        {
            CreateNewLayoutItem(enumLayoutTypeSimple.Group);
        }

        /// <summary>
        /// 新Item
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuItemNewLayoutItem_Click(object sender, EventArgs e)
        {
            CreateNewLayoutItem(enumLayoutTypeSimple.Item);
        }

        /// <summary>
        /// 新空Item
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuItemNewEmptyItem_Click(object sender, EventArgs e)
        {
            CreateNewLayoutItem(enumLayoutTypeSimple.EmptyItem);
        }

        /// <summary>
        /// 新布局
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuItemNewLayout_Click(object sender, EventArgs e)
        {
            if (treeLayout.Nodes.Count < 1)
            {
                CreateNewLayoutItem(enumLayoutTypeSimple.Base);
            }
            else
            {
                MessageBox.Show("布局控件只能有一个");
            }
        }

        /// <summary>
        /// 删除布局
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuItemDeleteLayout_Click(object sender, EventArgs e)
        {
            if (treeLayout.FocusedNode.ParentNode != null && treeLayout.FocusedNode.ParentNode.ParentNode == null)
            {
                for (int i = 0; i < treeLayout.AllNodesCount; i++)
                {
                    customPropertyGrid1.dicRemove(treeLayout.FindNodeByID(i).GetValue(4).ToString());
                }
                customPropertyGrid1.treeProperty.Nodes.Clear();
                treeLayout.DeleteNode(treeLayout.FocusedNode.ParentNode);
                return;
            }


            DeleteLayout(treeLayout.FocusedNode);
            customPropertyGrid1.treeProperty.Nodes.Clear();
            treeLayout.DeleteNode(treeLayout.FocusedNode);
        }

        /// <summary>
        /// 递归删除节点和所有子节点的内存值
        /// </summary>
        /// <param name="node"></param>
        private void DeleteLayout(TreeListNode node)
        {
            if (node.HasChildren)
            {
                foreach (TreeListNode tn in node.Nodes)
                {
                    DeleteLayout(tn);
                    //customPropertyGrid1.dicRemove(tn.GetValue(4).ToString());
                }
            }
            customPropertyGrid1.dicRemove(node.GetValue(4).ToString());
        }


        /// <summary>
        /// 菜单打开事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void contextMenuLayout_Opening(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (treeLayout.Nodes.Count > 0)
            {
                if (treeLayout.FocusedNode.GetValue(0) != null)
                {
                    if (treeLayout.FocusedNode.GetValue(0).ToString() == "Item" || treeLayout.FocusedNode.GetValue(0).ToString() == "Empty" || treeLayout.FocusedNode.GetValue(0).ToString() == "Base")
                    {
                        menuItemNewLayout.Enabled = false;
                        menuItemNewGroup.Enabled = false;
                        menuItemNewEmptyItem.Enabled = false;
                        menuItemNewLayoutItem.Enabled = false;
                        menuItemDeleteLayout.Enabled = true;
                    }
                    else
                    {
                        menuItemNewLayout.Enabled = false;
                        menuItemNewGroup.Enabled = true;
                        menuItemNewEmptyItem.Enabled = true;
                        menuItemNewLayoutItem.Enabled = true;
                        menuItemDeleteLayout.Enabled = true;
                    }
                }
            }
            else
            {
                menuItemNewLayout.Enabled = true;
                menuItemNewGroup.Enabled = false;
                menuItemNewEmptyItem.Enabled = false;
                menuItemNewLayoutItem.Enabled = false;
                menuItemDeleteLayout.Enabled = false;
            }
        }
        #endregion


        #region 其他控件事件

        /*控件下拉列表----------------------------------------------------------------------------------------*/
        /// <summary>
        /// 控件下拉菜单选中以后填充值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rsItemPopupContainerLayout_QueryResultValue(object sender, DevExpress.XtraEditors.Controls.QueryResultValueEventArgs e)
        {
            try
            {
                if (e.Value != treeItemForPopup.FocusedNode.GetValue(1))
                {
                    e.Value = treeItemForPopup.FocusedNode.GetValue(1) == null ? "" : treeItemForPopup.FocusedNode.GetValue(1);
                    treeLayout.FocusedNode.SetValue(1, e.Value);
                    if (HasSameName(e.Value.ToString().Trim(), true))
                    {
                        DialogResult show = MessageBox.Show("已选择过相同控件，请返回修改");
                        e.Value = "";
                        treeLayout.FocusedNode.SetValue(1, "");
                        treeLayout.FocusedNode.SetValue(5, "");
                        LayoutClickAndGetLayoutInfo();
                        return;
                    }
                }
                if (treeLayout.FocusedNode.GetValue(5) == null || String.IsNullOrEmpty(treeLayout.FocusedNode.GetValue(5).ToString()))
                {
                    treeLayout.FocusedNode.SetValue(5, treeItemForPopup.FocusedNode.GetValue(2));
                }
                LayoutClickAndGetLayoutInfo();
            }
            catch
            { }

        }

        /// <summary>
        /// 控件下拉菜单再次下拉时焦点置于选中的控件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rsItemPopupContainerLayout_Popup(object sender, EventArgs e)
        {
            if (treeLayout.FocusedNode.GetValue(1) != null)
            {
                if (!String.IsNullOrEmpty(treeLayout.FocusedNode.GetValue(1).ToString()))
                {
                    TreeListNode node = treeItemForPopup.FindNodeByFieldValue("BuildName", treeLayout.FocusedNode.GetValue(1).ToString());
                    node.TreeList.FocusedNode = node;
                    treeItemForPopup.SetFocusedNode(node);
                    node.Selected = true;
                }
            }
        }

        /// <summary>
        /// 控件下拉菜单数据源绑定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rsItemPopupContainerLayout_QueryPopUp(object sender, System.ComponentModel.CancelEventArgs e)
        {
            treeItemForPopup.Nodes.Clear();
            foreach (TreeListNode tln in treeControls.Nodes)
            {
                TreeListNode tn = treeItemForPopup.AppendNode(null, null);
                tn.SetValue(0, tln.GetValue(0));
                tn.SetValue(1, tln.GetValue(1));
                tn.SetValue(2, tln.GetValue(5));
                tn.ImageIndex = tln.ImageIndex;
                tn.StateImageIndex = tln.StateImageIndex;
            }
        }



        #endregion




















    }
}
